package com.young.shop.api.configurations;

import com.alibaba.fastjson.JSON;
import com.young.shop.api.service.TbMessageService;
import com.young.shop.pojo.entity.TbMessage;
import com.young.shop.pojo.entity.MessageQOVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//@ServerEndpoint注解中的内容是用户客户端websocket的连接url,例如ws://127.0.0.1:80/websocket/ws,
//结构形式为“ws：//ip:端口/项目名/指定的url”
@Component
@ServerEndpoint("/WS/{userName}")
public class WebSocket {

    //public static CopyOnWriteArrayList<WebSocket> WebSocketList = new CopyOnWriteArrayList();
    public static Map<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();

    private String userName;
    private Session session;

    public static TbMessageService tbMessageService;

    @Autowired
    public void setApplicationContext(TbMessageService tbMessageService) {
        WebSocket.tbMessageService = tbMessageService;
    }

    //连接打开时执行
    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName) {

        this.userName = userName;
        this.session = session;
        webSocketMap.put(userName, this);

        System.out.println("sessionid：" + session.getId());
        System.out.println(userName);

        //发送历史消息
        List<TbMessage> listTbMessageByRecipient = tbMessageService.findListTbMessageByRecipient(this.userName);
        listTbMessageByRecipient.forEach(item -> {
            if (userName.equals(userName)) {
                String jsonString = JSON.toJSONString(item);
                sendToThis(jsonString);
            }
        });

    }


    //收到消息时执行---------------------------------------------------------------------------
    @OnMessage
    public void onMessage(String message, Session session) {

        //用户向商家发消息
        if (!"商家".equals(userName)) {
            MessageQOVO messageQOVO = new MessageQOVO();
            messageQOVO.setSender(this.userName);
            messageQOVO.setMessage(message);
            sendToCustomerService(messageQOVO);
        }


        //商家向用户发消息
        if ("商家".equals(userName)) {
            MessageQOVO messageQO = JSON.parseObject(message, MessageQOVO.class);
            System.out.println(messageQO);
            messageQO.setSender("商家");
            sendToUser(messageQO);
        }

    }
    //收到消息时执行---------------------------------------------------------------------------


    //连接关闭时执行
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        WebSocket.webSocketMap.remove(this.userName);
        System.out.println("客户端关闭,sessionid：" + session.getId());
    }


    //连接错误时执行
    @OnError
    public void onError(Throwable t) {
        WebSocket.webSocketMap.remove(this.userName);
        t.printStackTrace();
    }


    public void sendToCustomerService(MessageQOVO messageVO) {
        try {
            //商家在线时
            String jsonString = JSON.toJSONString(messageVO);
            WebSocket webSocket = WebSocket.webSocketMap.get("商家");
            webSocket.session.getBasicRemote().sendText(jsonString);
            //将已读消息存入数据库
            tbMessageService.addOMessageReadStateIs1(this.userName, "商家", messageVO.getMessage());
        } catch (Exception e) {
            //商家不在线时,将未读消息存入数据库
            System.out.println("商家不在线");
            tbMessageService.addOneMessage(this.userName, "商家", messageVO.getMessage());
        }
    }

    public void sendToUser(MessageQOVO messageQO) {
        String jsonString = JSON.toJSONString(messageQO);
        String recipient = messageQO.getRecipient();
        String message = messageQO.getMessage();
        try {
            WebSocket webSocket = WebSocket.webSocketMap.get(recipient);
            webSocket.session.getBasicRemote().sendText(jsonString);
            tbMessageService.addOMessageReadStateIs1(this.userName, recipient, message);
        } catch (Exception e) {
            System.out.println("对应用户已下线");
            tbMessageService.addOneMessage(this.userName, recipient, message);
        }
    }

    public void sendToThis(String jsonString) {
        try {
            session.getBasicRemote().sendText(jsonString);
        } catch (Exception e) {

        }
    }

}